package com.zhdl.websocket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhdl.common.ytools.HttpClientUtil;
import com.zhdl.common.ytools.PublicTools;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author: liu zhenming
 * @date: 2023/8/18 9:18
 */
@Slf4j
public class WebSocketRunClient extends WebSocketClient {

    /**
     * websocket连接名称
     */
    private final String websocketName;

    public WebSocketRunClient(URI serverUri, String websocketName) {
        super(serverUri);
        this.websocketName = websocketName;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("websocket 客户端 onOpen");
    }

    @Override
    public void onMessage(String s) {

        /*
            心跳检测不处理
         */
        if(s.contains("client_")) return;
        if(s.contains("areaList")) return;

        /*
            打印收到的信息
         */
        log.info("websocket 客户端 message : {}", s);

        try{
            /*
                转换成 json 格式，打印
             */
            JSONObject jsonObject = new JSONObject(s);
            String ctrlCode=(String)jsonObject.get("msg");
            if (ctrlCode != null && !ctrlCode.isEmpty()){
                if(ctrlCode.equalsIgnoreCase("clear_alarm")) {
                    //pwd=26c0518a6508198645f16e61d5388ed7
                    //areaId=d4ea14a9f12647af9d25b62ebebc7644
                    Map<String, Object> params = new HashMap<>();
                    params.put("pwd","26c0518a6508198645f16e61d5388ed7");
                    params.put("areaId","d4ea14a9f12647af9d25b62ebebc7644");
                    HttpClientUtil.post("http://127.0.0.1:8086/api/v1/com/clear/alarm",params);
                    HttpClientUtil.get("http://127.0.0.1:8086/api/v1/test/ctrl/alarm/light/true");
                }
                System.out.println("[websocket:"+websocketName+"收到String消息"+ctrlCode);
            }
//            String jsonStr = JSONUtil.toJsonStr(s);
//            System.out.println("[websocket:"+websocketName+"收到String消息"+jsonStr);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            log.info("websocket错误信息为" + e.getMessage());
        }
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("Connection closed by " + (b ? "remote peer" : "us") + " Code: " + i + " Reason: " + s);
    }

    @Override
    public void onError(Exception e) {
        log.error("websocket 客户端 error {}", e.getMessage());
    }


}
